package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.CategoryBrandRelationDao;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    CategoryBrandRelationDao categoryBrandRelationDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            wrapper.eq(BrandEntity::getBrandId,key).or().like(BrandEntity::getName,key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateDetail(BrandEntity brand) {
        //先更新我自己对应的表
        baseMapper.updateById(brand);
        //在name不为空的情况下
        //因为在pms_category_brand_relation表中
        //是有brand_id以及brand_name，你更新冗余字段brand_name
        if (!StringUtils.isEmpty(brand.getName())){
            Long brandId = brand.getBrandId();
            CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
            entity.setBrandId(brandId);
            entity.setBrandName(brand.getName());
            //下面这个UpdateWrapper专门用于更新where后面的限制条件
            UpdateWrapper<CategoryBrandRelationEntity> wrapper = new UpdateWrapper<>();
            //where brand_id=brand.getBrandId()
            wrapper.eq("brand_id",brand.getBrandId());
            categoryBrandRelationDao.update(entity,wrapper);
            //TODO 其他的更新
        }
    }
}